package com.github.maojx0630.wechat.bot.monitor;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.zhxu.okhttps.WebSocket;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.github.maojx0630.wechat.bot.dto.NewMsgDto;
import com.github.maojx0630.wechat.bot.reverse.WebsocketComponent;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author 毛家兴
 * @since 2024-04-17 11:25
 */
@Slf4j
@Component
public class WechatMonitor {

  private WebSocket webSocket;

  private final WechatUtil wechatUtil;

  private final WebsocketComponent websocketComponent;

  public WechatMonitor(WechatUtil wechatUtil, WebsocketComponent websocketComponent) {
    this.wechatUtil = wechatUtil;
    this.websocketComponent = websocketComponent;
    reconnect();
  }

  public void send(String text) {
    webSocket.send(text);
  }

  private void reconnect() {
    this.webSocket =
        wechatUtil
            .getHttp()
            .webSocket("/ws/generalMsg")
            .setOnOpen(
                (ws, data) -> {
                  log.info("连接成功 : {}", data);
                })
            .setOnClosed(
                (ws, data) -> {
                  log.info("连接关闭 : {}", data);
                  ThreadUtil.execute(
                      () -> {
                        ThreadUtil.sleep(1000L);
                        log.info("等待一秒尝试重连");
                        reconnect();
                      });
                })
            .setOnException(
                (ws, data) -> {
                  log.error("连接异常 : ", data);
                })
            .setOnMessage(
                (ws, data) -> {
                  NewMsgDto newMsgDto = JSON.parseObject(data.toString(), NewMsgDto.class);
                  if (newMsgDto.getTotal() > 0) {
                    for (NewMsgDto.DataBean item :
                        newMsgDto.getData().stream()
                            .filter(
                                obj -> {
                                  if (StrUtil.isNotBlank(obj.getCreateTime())) {
                                    if (DateUtil.between(
                                            new Date(),
                                            new Date(1000L * Long.parseLong(obj.getCreateTime())),
                                            DateUnit.SECOND)
                                        < 5) {
                                      return true;
                                    }
                                  }
                                  return false;
                                })
                            .toList()) {
                      if (StrUtil.isNotBlank(item.getCreateTime())) log.info("收到消息 : {}", item);
                      if (StrUtil.endWith(item.getStrTalker(), "@chatroom")
                          && "0".equals(item.getIsSender())
                          && "1".equals(item.getType())
                          && (StrUtil.startWith(item.getStrContent(), "!")
                              || StrUtil.startWith(item.getStrContent(), "！"))) {
                        JSONObject json = new JSONObject();
                        json.put("sender", item.getSender());
                        json.put("content", item.getStrContent());
                        json.put("talker", item.getStrTalker());
                        websocketComponent.send(json.toString());
                      }
                    }
                  }
                })
            .listen();
  }
}
